package ds_industry_2025.industry.gy_04.T3

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

/*
    2、编写Scala代码，使用Spark根据dwd_ds_hudi层的fact_change_record表统计每个月（change_start_time的月份）、每个设备、
    每种状态的时长，若某状态当前未结束（即change_end_time值为空）则该状态不参与计算。计算结果存入ClickHouse数据
    库shtd_industry的machine_state_time表中（表结构如下），然后在Linux的ClickHouse命令行中根据设备id、状态持续时长均为降
    序排序，查询出前10条，将SQL语句复制粘贴至客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下，将执行结果截图粘贴
    至客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下;
 */
object t5 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t1")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

      val hdfs="hdfs://192.168.40.110:9000/user/hive/warehouse/hudi_gy_dwd.db/fact_change_record"

    spark.read.format("hudi").load(hdfs)
      .where(col("changeendtime").isNotNull)
      .createOrReplaceTempView("data")




    val r2 = spark.sql(
      """
        |select distinct
        |machine_id,
        |change_record_state,
        |sum(run_time) over(partition by year,month,machine_id,change_record_state) as duratime,
        |year,month
        |from(
        |select
        |changemachineid as machine_id,
        |changerecordstate as change_record_state,
        |(unix_timestamp(changeendtime) - unix_timestamp(changestarttime)) as run_time ,
        |year(changestarttime) as year,
        |month(changeendtime) as month
        |from data
        |) as r1
        |""".stripMargin)

    r2.write.format("jdbc")
      .option("url","jdbc:clickhouse://192.168.40.110:8123/shtd_industry")
      .option("user","default")
      .option("password","")
      .option("driver","com.clickhouse.jdbc.ClickHouseDriver")
      .option("dbtable","machine_state_time")
      .save()


    spark.close()
  }

}
